<template>
  <div>
    <a-modal :visible="visible" title="AI扩写" :bodyStyle="{
        padding: '20px 60px',
      }" :width="800" :footer="null" @cancel="cancelClick" destroyOnClose>
      <a-spin :spinning="submitLoading" > 

      <a-alert message="提示" description="仅需一个示例标题，其它交给AI帮你写~ 更丰富的视频标题，视频发布效果更好哦~" type="info" show-icon closable
        @close="onClose" style="margin-bottom: 20px">
        <template #icon><info-circle-filled /></template>
      </a-alert>
      <a-form :label-col="{ span: 5 }">
        <a-form-item label="关键词组" name="ai_keyword_group_id">
          <a-select :options="keyWordsGroupList" v-model:value="modelRef.ai_keyword_group_id" placeholder="请输入关键词"
            allowClear @change="groupSelChange" :filter-option="filterOption"></a-select>
        </a-form-item>
        <a-form-item label="关键词" name="ai_keyword_id">
          <a-select :filter-option="filterOption" :options="keyWordsList" v-model:value="modelRef.ai_keyword_id"
            placeholder="请输入关键词" allowClear></a-select>
        </a-form-item>
        <!-- <a-form-item label="是否包含关键词" v-bind="validateInfos.contain">
          <a-radio-group v-model:value="modelRef.contain">
            <a-radio :value="1">包含</a-radio>
            <a-radio :value="0">不包含</a-radio>
          </a-radio-group>
        </a-form-item> -->
        <a-form-item label="示例标题" v-bind="validateInfos.content">
          <a-button type="link" @click="openMaterial">文案导入</a-button>
          <a-textarea v-model:value="modelRef.content" show-count :maxlength="500" :rows="13" />
        </a-form-item>
        <a-form-item label="扩写数量" v-bind="validateInfos.num">
          <a-input-number :disabled="isone_num" id="inputNumber" v-model:value="modelRef.num" style="width: 300px" />
        </a-form-item>
        <!-- <a-form-item label="规则">
          <div style="margin-top: 10px; color: #aaaaaa">
            每次扩写将消耗AI创作字数
            <div>
              剩余字数：{{ creation_num }}
              <span style="
                  color: var(--ss-primary-color);
                  cursor: pointer;
                  margin-left: 15px;
                " @click="goPay">去充值></span>
            </div>
          </div>
        </a-form-item> -->
      </a-form>
      <div class="footer">
        <a-space>
          <a-button @click="cancelClick" type="primary" class="cancel">取消</a-button>
          <a-button :loading="submitLoading" type="primary" class="confirm" @click="confirmClick">确定</a-button>
        </a-space>
      </div>
     </a-spin>

    </a-modal>

  </div>
  <ChooseMaterial :isClip="true" material_type="text" :multiple="false" :visible="materiallibraryShow"
    @close="closeChooseMaterial($event, 'material_type')" />

      <!-- 文案库 -->
  <CopyLibraryModal ref="copyLibraryModal" @importSuccess="audioLItemImportSuccess" />
  <vipModal :visible="vipVisible" @close="vipVisible = false"></vipModal>

</template>

<script>
import { computed, defineComponent, reactive, toRefs,ref, watch } from "vue";
import { InfoCircleFilled, InfoCircleOutlined } from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import { Form } from "ant-design-vue";
const useForm = Form.useForm;
import { message } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";
import vipModal from '@/socialMedia/Vip/vipModal.vue'
import utils from "@/common/utils/utils.js";
// 素材库
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";

// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";
export default defineComponent({
  name: "NewClip",
  components: {
    InfoCircleFilled,
    InfoCircleOutlined,
    ChooseMaterial,
    vipModal,
    CopyLibraryModal
  },
  props: {
    imgeUrl: {
      type: String,
      default: "",
    },
    isone_num: {
      type: Boolean,
      default: false
    },
      TextContent: {
    type: String,
    default: "",
  }
  },
  setup(props, { emit }) {
    const router = useRouter();
    const state = reactive({
      visible: false,
      submitLoading: false, //提交按钮loading
      creation_num: 0,
      keyWordsGroupList: [], //关键词组下拉列表
      keyWordsList: [], //关键词下拉列表
      AIloading: false, //AI扩写loading
      AIexpansionCount: 0, //AI扩写生成数量
      AIexpansionTotal: 0, //AI扩写总数
      keyWordsSping: false, //关键词下拉框loading
      materiallibraryShow: false, //控制素材库显示隐藏
      copyLibraryModal: null
    });
    // 充值弹窗
    const vipModalRef = ref(null)
    const vipVisible = ref(false)
    // 开启弹窗
    const showModal = (param={}) => {
      const { text } = param
      text && (modelRef.content = text)
      state.visible = true;
      getRights();
      getOptionList();
    };
    // 关闭弹窗
    const cancelClick = () => {
      state.visible = false;
      resetData();
    };
    const modelRef = reactive({
      content: "",
      num: 1,
      ai_keyword_group_id: null, //关键词组id
      ai_keyword_id: null, //关键词id
      contain: 1, //是否包含关键词（1：包含，0：不包含）
    });
    const rulesRef = reactive({
      content: [
        {
          required: true,
          message: "请输入示例标题",
        },
      ],
      num: [
        {
          required: true,
          message: "请输入生成数量",
          trigger: 'change'
        },
        {
          validator: (rule, value) => {
            if (value < 1 || value > 5) {
              return Promise.reject(new Error("生成数量必须在 1 到 5 之间"));
            }
            return Promise.resolve();
          },
          trigger: 'change'
        }
      ],
      contain: [
        {
          required: true,
          message: "请选择是否包含关键词",
        },
      ],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const confirmClick = () => {
      validate().then(async() => {
        try {
          // 查看用户的点数是否足够消耗
          await utils.aiTextGet()
          try {
            // 消耗规则
            const rule = await utils.consumptionPointRule()
            // 获取提示
            const content = utils.ruleTips({ res: rule, key: "ai_text_point" })
            // 弹出提示
            await utils.md({ content })
            // 弹窗确认消耗
          } catch (error) {
            return
          }
        } catch (error) {
          // 打开充值, 接着打开点数购买
          vipVisible.value = true
          vipModalRef.value && vipModalRef.value.openBuyVisible()
          return
        }

        state.submitLoading = true; //提交按钮loading加载
        state.AIloading = true; //开启AI扩写loading
        request
          .post("/work_ai", "/user/filmrelease/ai/generate_title", {
            ...modelRef,
          })
          .then((res) => {
            // 判断是否返回了task_id
            if (res.result) {
              const task_id = res.result; //用于轮询请求状态的task_id
            
              state.AIexpansionTotal = modelRef.num; //预生成总数
              // state.visible = false; //关闭弹窗,开启轮询
              let intervalId = setInterval(() => {
                request
                  .get(
                    "/work_ai",
                    "/user/filmrelease/ai/generate_title/status",
                    { task_id: task_id }
                  )
                  .then((successRes) => {
                    let arr = [];
                    arr = successRes.result.data.map((item) => {
                      return {
                        text: item, //标题
                        ai_keyword_group_id: modelRef.ai_keyword_group_id, //关键词组id
                        ai_keyword_id: modelRef.ai_keyword_id, //关键词id
                        keyWordsGroupList: state.keyWordsGroupList, //关键词组下拉列表
                        keyWordsList: state.keyWordsList, //关键词下拉列表
                      };
                    });
                    state.AIexpansionCount = arr.length; //已生成数量
                    if (arr.length) {
                      state.submitLoading = false; //关闭提交按钮loading
                      emit("onConfirm", arr); //提交请求结果
                    }
                    // 请求成功或者失败
                    if (
                      successRes.result.status == "success" ||
                      successRes.result.status == "error"
                    ) {
                      clearInterval(intervalId); // 清除定时器，停止轮询
                      setTimeout(() => {
                        state.AIloading = false; //关闭AI加载状态
                        state.AIexpansionCount = 0;
                        state.AIexpansionTotal = 0;
                        resetData(); //重置数据
                      }, 1000);
                    }
                  })
                  .catch((errRes) => {
                    // 轮询接口出错
                    clearInterval(intervalId); //清除定时器
                    state.submitLoading = false; //关闭提交按钮loading
                    state.AIloading = false; //关闭AI 扩写loading状态
                  });
              }, 3000);
            } else {
              // 没有返回task_id
              message.error("生成失败,task_id丢失");
              state.submitLoading = false; //关闭提交按钮loading
              state.AIloading = false; //关闭AI 扩写loading状态
            }
          })
          .catch((err) => {
            state.submitLoading = false; //关闭按钮loading
            state.AIloading = false; //关闭AI扩写loading
          });
      });
    };
    // 重置数据
    const resetData = () => {
      modelRef.content = "";
      modelRef.num = 1;
      modelRef.word = [];
      modelRef.contain = 0;
      modelRef.ai_keyword_id = null;
      modelRef.ai_keyword_group_id = null;
      state.keyWordsGroupList = [];
      state.keyWordsList = [];
    };

    const getRights = () => {
      request.get("/work_ai", "/user/shotstack/user/rights").then((res) => {

        console.log(res,  '文案仿写的扣费规则');
        state.creation_num = res.result?.creation_num;
      });
    };

    const goPay = () => {
      router.push({
        name: "VoucherCenter",
      });
    };
    // 获取关键词组下拉列表
    const getOptionList = () => {
      request
        .get("/work_ai", "/user/filmrelease/ai/keyword", { pagesize: 0 })
        .then((res) => {
          state.keyWordsGroupList = res.result?.data?.map((item) => {
            return {
              label: item.extraction_word,
              value: item.id,
            };
          });
        })
        .finally(() => {});
    };
    // 获取关键词下拉列表
    const groupSelChange = () => {
      modelRef.ai_keyword_id = null;
      state.AI_keyword_group_id = modelRef.ai_keyword_group_id;
      state.keyWordsList = [];
      if (modelRef.ai_keyword_group_id) {
        let params = {
          page: 0,
          ai_keyword_id: modelRef.ai_keyword_group_id,
          word: "",
        };
        state.keyWordsSping = true;
        request
          .get("/work_ai", "/user/filmrelease/ai/keywordMerge/list", params)
          .then((successRes) => {
            state.keyWordsList = successRes?.result?.map((ele) => {
              return {
                value: ele.id,
                label: ele.merge_keyword,
              };
            });
            state.keyWordsSping = false;
          })
          .catch((errorRes) => {
            state.keyWordsSping = false;
          });
      }
    };
    // 输入关键词
    const keyWordsChange = (event) => {
      if (event.length && event[event.length - 1].length > 5) {
        message.warning("关键词长度不能超过5个字符");
        modelRef.word[modelRef.word.length - 1] = modelRef.word[
          modelRef.word.length - 1
        ].substring(0, 5);
      }
      if (modelRef.word.length > 3) {
        message.warning("最多添加3个关键词");
        modelRef.word = modelRef.word.filter((tag, index) => index < 3);
      }
    };
    // 文案导入
    const openMaterial = () => {
      // state.materiallibraryShow = true;
       state.copyLibraryModal && state.copyLibraryModal.showModal();

    };

        // 文案库导入成功回调
    const audioLItemImportSuccess = (data) => {
  console.log(data,  '文案库的回调111111');
  if (data.length) {
     modelRef.content = data[0].material_content;
  }
};
    // 素材选择回调
    const closeChooseMaterial = (data) => {
      console.log(data);
      if (data && data.material_content !== "") {
        modelRef.content = data.material_content;
      }
      state.materiallibraryShow = false;
    };


    // AI扩写请求状态
    const AILoading = computed(() => {
      return state.AIloading;
    });
    // AI扩写已生成数量
    const AIExpanSionCount = computed(() => {
      return state.AIexpansionCount;
    });
    // AI扩写总数量
    const AIExpanSionTotal = computed(() => {
      return state.AIexpansionTotal;
    });

    watch(
      () => props.TextContent,
      (val) => {
        modelRef.content = val
      },
      {
        immediate: true,
      }
    );



    return {
      showModal,
      cancelClick,
      confirmClick,
      vipModalRef,
      vipVisible,

      validateInfos,
      resetFields,
      modelRef,
      ...toRefs(state),
      goPay,
      keyWordsChange,
      getOptionList,
      resetData,
      AILoading,
      AIExpanSionCount,
      AIExpanSionTotal,
      groupSelChange,
      openMaterial,
      closeChooseMaterial,
      audioLItemImportSuccess
    };
  },
});
</script>

<style lang="less" scoped>
.content {
  text-align: center;
  padding: 20px;
  color: #c2c2c2;
}

.footer {
  text-align: right;
  padding-top: 10px;

  .cancel {
    border-radius: 5px;
    background: #fff;
    border: 1px solid #e0e0e6;
    color: #000;
  }

  .confirm {
    border-radius: 5px;
    background: #2878ff;
    border: none;
  }
}

.temp_title {
  width: 100%;
  border: 1px solid #d9d9d9;
  height: 50px;
  padding: 10px;
}
</style>
